package com.sxf.redis.starter;



import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.ConfigSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import com.sxf.common.exceptions.InternalException;
import com.sxf.redis.RedisClient;
import com.sxf.redis.properties.RedissonProperties;
import com.sxf.utils.JacksonUtils;

/**
 * @description: redisson启动项
 * @author: zhangyb@ccccit.com.cn
 * @date: 2020年12月31日 上午10:57:19
 */
@EnableConfigurationProperties({RedissonProperties.class})
public class AutoRedissonStarter {

	@Value("${spring.application.name:default_app}")
	private String springApplicationName;

	@Value("${spring.profiles.active:default_env}")
	private String env;

	@Autowired
	private RedissonProperties redissonProperties;


	private RedissonClient redisson() {
		Config config = null;
		try {
			ConfigSupport support = new ConfigSupport();
			config = support.fromJSON(JacksonUtils.toJsonString(redissonProperties), Config.class);
			config.setCodec(new JsonJacksonCodec());
		} catch (Exception e) {
			throw new InternalException("初始化redis失败", e);
		}
		return Redisson.create(config);
	}

	@Bean
	public RedisClient generateRedisClient() {
		return new RedisClient(redisson(), springApplicationName, env);
	}

}
